'use client';

import React, { useState, useEffect } from 'react';
import {
  Modal,
  Tree,
  Input,
  Button,
  Space,
  message,
  Spin,
  Tabs,
  Card,
  Tag,
  Checkbox,
  Row,
  Col,
  Typography,
  Divider,
  Alert
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  SaveOutlined,
  CloseOutlined,
  CheckOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';

const { Search } = Input;
const { TabPane } = Tabs;
const { Text, Title } = Typography;

interface Permission {
  id: string;
  name: string;
  display_name: string;
  description?: string;
  category: string;
  resource_type: string;
  action: string;
  is_system: boolean;
  is_active: boolean;
  assigned?: boolean;
  assignedAt?: string;
}

interface Role {
  id: string;
  name: string;
  display_name: string;
  description?: string;
  level: number;
  is_system: boolean;
  is_active: boolean;
}

interface PermissionConfigModalProps {
  visible: boolean;
  role: Role | null;
  onCancel: () => void;
  onSuccess: () => void;
}

interface PermissionsByCategory {
  [category: string]: Permission[];
}

const PermissionConfigModal: React.FC<PermissionConfigModalProps> = ({
  visible,
  role,
  onCancel,
  onSuccess
}) => {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [permissionsByCategory, setPermissionsByCategory] = useState<PermissionsByCategory>({});
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);
  const [searchText, setSearchText] = useState('');
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [activeTab, setActiveTab] = useState('tree');

  // 获取角色权限数据
  const fetchRolePermissions = async () => {
    if (!role) return;
    
    setLoading(true);
    try {
      const response = await fetch(`/api/admin/roles/${role.id}/permissions`);
      const result = await response.json();
      
      if (result.success) {
        const permissionsData = result.data.permissions || [];
        setPermissions(permissionsData);
        
        // 按类别分组
        const grouped = permissionsData.reduce((acc: PermissionsByCategory, permission: Permission) => {
          const category = permission.category || 'other';
          if (!acc[category]) {
            acc[category] = [];
          }
          acc[category].push(permission);
          return acc;
        }, {});
        setPermissionsByCategory(grouped);
        
        // 设置已选中的权限
        const assignedIds = permissionsData
          .filter((p: Permission) => p.assigned)
          .map((p: Permission) => p.id);
        setSelectedPermissions(assignedIds);
        setCheckedKeys(assignedIds);
        
        // 默认展开所有类别
        setExpandedKeys(Object.keys(grouped));
      } else {
        message.error(result.error || '获取权限数据失败');
      }
    } catch (error) {
      message.error('网络错误');
    } finally {
      setLoading(false);
    }
  };

  // 保存权限配置
  const handleSave = async () => {
    if (!role) return;
    
    setSaving(true);
    try {
      const response = await fetch(`/api/admin/roles/${role.id}/permissions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          permissionIds: selectedPermissions
        })
      });
      
      const result = await response.json();
      
      if (result.success) {
        message.success(result.message || '权限配置保存成功');
        onSuccess();
        onCancel();
      } else {
        message.error(result.error || '保存权限配置失败');
      }
    } catch (error) {
      message.error('网络错误');
    } finally {
      setSaving(false);
    }
  };

  // 构建权限树数据
  const buildTreeData = (): DataNode[] => {
    const filteredCategories = Object.entries(permissionsByCategory).filter(([category, perms]) => {
      if (!searchText) return true;
      return perms.some(p => 
        p.display_name.toLowerCase().includes(searchText.toLowerCase()) ||
        p.description?.toLowerCase().includes(searchText.toLowerCase()) ||
        p.name.toLowerCase().includes(searchText.toLowerCase())
      );
    });

    return filteredCategories.map(([category, perms]) => {
      const filteredPerms = perms.filter(p => {
        if (!searchText) return true;
        return p.display_name.toLowerCase().includes(searchText.toLowerCase()) ||
               p.description?.toLowerCase().includes(searchText.toLowerCase()) ||
               p.name.toLowerCase().includes(searchText.toLowerCase());
      });

      return {
        title: (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span>{getCategoryDisplayName(category)}</span>
            <Tag color="blue">{filteredPerms.length}</Tag>
          </div>
        ),
        key: category,
        children: filteredPerms.map(permission => ({
          title: (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{ fontWeight: 500 }}>{permission.display_name}</span>
                {permission.is_system && <Tag color="orange">系统</Tag>}
                {permission.assigned && <Tag color="green">已分配</Tag>}
              </div>
              {permission.description && (
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  {permission.description}
                </Text>
              )}
              <Text type="secondary" style={{ fontSize: '11px' }}>
                {permission.name} | {permission.resource_type}:{permission.action}
              </Text>
            </div>
          ),
          key: permission.id,
          isLeaf: true
        }))
      };
    });
  };

  // 获取类别显示名称
  const getCategoryDisplayName = (category: string): string => {
    const categoryNames: { [key: string]: string } = {
      'user_management': '用户管理',
      'role_management': '角色管理', 
      'permission_management': '权限管理',
      'page_access': '页面访问',
      'ai_features': 'AI功能',
      'system_settings': '系统设置',
      'content_management': '内容管理',
      'other': '其他'
    };
    return categoryNames[category] || category;
  };

  // 处理权限选择变化
  const handlePermissionCheck = (checkedKeysValue: any) => {
    const permissionIds = checkedKeysValue.filter((key: string) => 
      permissions.some(p => p.id === key)
    );
    setCheckedKeys(checkedKeysValue);
    setSelectedPermissions(permissionIds);
  };

  // 全选/取消全选类别
  const handleCategoryToggle = (category: string, checked: boolean) => {
    const categoryPermissions = permissionsByCategory[category] || [];
    const categoryPermissionIds = categoryPermissions.map(p => p.id);
    
    let newSelectedPermissions: string[];
    if (checked) {
      newSelectedPermissions = [...new Set([...selectedPermissions, ...categoryPermissionIds])];
    } else {
      newSelectedPermissions = selectedPermissions.filter(id => !categoryPermissionIds.includes(id));
    }
    
    setSelectedPermissions(newSelectedPermissions);
    setCheckedKeys(newSelectedPermissions);
  };

  // 重置选择
  const handleReset = () => {
    const assignedIds = permissions
      .filter(p => p.assigned)
      .map(p => p.id);
    setSelectedPermissions(assignedIds);
    setCheckedKeys(assignedIds);
  };

  // 全选所有权限
  const handleSelectAll = () => {
    const allPermissionIds = permissions.map(p => p.id);
    setSelectedPermissions(allPermissionIds);
    setCheckedKeys(allPermissionIds);
  };

  // 清空所有选择
  const handleClearAll = () => {
    setSelectedPermissions([]);
    setCheckedKeys([]);
  };

  useEffect(() => {
    if (visible && role) {
      fetchRolePermissions();
    }
  }, [visible, role]);

  const treeData = buildTreeData();
  const selectedCount = selectedPermissions.length;
  const totalCount = permissions.length;
  const assignedCount = permissions.filter(p => p.assigned).length;

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <InfoCircleOutlined />
          <span>配置角色权限</span>
          {role && (
            <Tag color={role.is_system ? 'orange' : 'blue'}>
              {role.display_name}
            </Tag>
          )}
        </div>
      }
      open={visible}
      onCancel={onCancel}
      width={900}
      style={{ top: 20 }}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          <CloseOutlined /> 取消
        </Button>,
        <Button key="reset" onClick={handleReset}>
          <ReloadOutlined /> 重置
        </Button>,
        <Button 
          key="save" 
          type="primary" 
          loading={saving}
          onClick={handleSave}
          disabled={!role}
        >
          <SaveOutlined /> 保存配置
        </Button>
      ]}
    >
      <div style={{ maxHeight: '70vh', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        {/* 统计信息 */}
        <Alert
          message={
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span>
                总权限: {totalCount} | 已分配: {assignedCount} | 当前选择: {selectedCount}
              </span>
              <Space>
                <Button size="small" onClick={handleSelectAll}>
                  全选
                </Button>
                <Button size="small" onClick={handleClearAll}>
                  清空
                </Button>
              </Space>
            </div>
          }
          type="info"
          style={{ marginBottom: 16 }}
        />

        {/* 搜索框 */}
        <Search
          placeholder="搜索权限名称或描述"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          style={{ marginBottom: 16 }}
          prefix={<SearchOutlined />}
        />

        {/* 权限配置内容 */}
        <div style={{ flex: 1, overflow: 'auto' }}>
          <Spin spinning={loading}>
            <Tabs activeKey={activeTab} onChange={setActiveTab}>
              <TabPane tab="树形视图" key="tree">
                <Tree
                  checkable
                  treeData={treeData}
                  checkedKeys={checkedKeys}
                  expandedKeys={expandedKeys}
                  onCheck={handlePermissionCheck}
                  onExpand={(expandedKeys) => setExpandedKeys(expandedKeys as string[])}
                  style={{ background: 'transparent' }}
                />
              </TabPane>
              
              <TabPane tab="分类视图" key="category">
                <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                  {Object.entries(permissionsByCategory).map(([category, perms]) => {
                    const filteredPerms = perms.filter(p => {
                      if (!searchText) return true;
                      return p.display_name.toLowerCase().includes(searchText.toLowerCase()) ||
                             p.description?.toLowerCase().includes(searchText.toLowerCase()) ||
                             p.name.toLowerCase().includes(searchText.toLowerCase());
                    });
                    
                    if (filteredPerms.length === 0) return null;
                    
                    const categoryPermissionIds = filteredPerms.map(p => p.id);
                    const selectedInCategory = categoryPermissionIds.filter(id => selectedPermissions.includes(id));
                    const allSelected = selectedInCategory.length === categoryPermissionIds.length;
                    const someSelected = selectedInCategory.length > 0;
                    
                    return (
                      <Card key={category} size="small">
                        <div style={{ marginBottom: 12 }}>
                          <Checkbox
                            checked={allSelected}
                            indeterminate={someSelected && !allSelected}
                            onChange={(e) => handleCategoryToggle(category, e.target.checked)}
                          >
                            <Title level={5} style={{ margin: 0, display: 'inline' }}>
                              {getCategoryDisplayName(category)}
                            </Title>
                            <Tag color="blue" style={{ marginLeft: 8 }}>
                              {selectedInCategory.length}/{filteredPerms.length}
                            </Tag>
                          </Checkbox>
                        </div>
                        
                        <Row gutter={[8, 8]}>
                          {filteredPerms.map(permission => (
                            <Col span={12} key={permission.id}>
                              <Checkbox
                                checked={selectedPermissions.includes(permission.id)}
                                onChange={(e) => {
                                  if (e.target.checked) {
                                    setSelectedPermissions([...selectedPermissions, permission.id]);
                                  } else {
                                    setSelectedPermissions(selectedPermissions.filter(id => id !== permission.id));
                                  }
                                }}
                              >
                                <div style={{ display: 'flex', flexDirection: 'column' }}>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                    <span style={{ fontSize: '13px', fontWeight: 500 }}>
                                      {permission.display_name}
                                    </span>
                                    {permission.is_system && <Tag color="orange">系统</Tag>}
                                    {permission.assigned && <Tag color="green">已分配</Tag>}
                                  </div>
                                  {permission.description && (
                                    <Text type="secondary" style={{ fontSize: '11px' }}>
                                      {permission.description}
                                    </Text>
                                  )}
                                </div>
                              </Checkbox>
                            </Col>
                          ))}
                        </Row>
                      </Card>
                    );
                  })}
                </div>
              </TabPane>
            </Tabs>
          </Spin>
        </div>
      </div>
    </Modal>
  );
};

export default PermissionConfigModal;